<template>
  <div class="docEditor">
    <div class="editor-container">
      <Toolbar
        class="editor-toolBar"
        :editor="editor"
        :mode="mode"
        :default-config="toolbarConfig"
      />
      <el-alert v-if="error" :title="error" type="error" />
      <div class="editor-main scrollbar-no-width">
        <div id="articleContent" class="ext-container">
          <el-form-item label-width="0">
            <el-input v-model="formRecord.title" maxlength="150" show-word-limit placeholder="请输入标题" class="input-title-value input-no-border" />
          </el-form-item>
          <el-form-item v-if="showInput.includes('author')" label-width="0">
            <el-input v-model="formRecord.author" maxlength="8" show-word-limit placeholder="请输入作者" class="input-no-border" />
          </el-form-item>
          <slot />
        </div>
        <Editor
          v-model="formRecord.content"
          style="overflow-y: hidden; "
          :style="{'min-height':height}"
          :mode="mode"
          :default-config="editorConfig"
          @onChange="onChange"
          @onCreated="onCreated"
        />
        <div class="ext-container bottom">
          <el-form-item v-if="showInput.includes('abstract')" label-width="0">
            <el-input
              v-model="formRecord.contnetAbstract"
              class="input-no-border"
              :min-rows="2"
              placeholder="选填，摘要会帮助读者快速了解内容"
              maxlength="200"
              autosize
              show-word-limit
              type="textarea" />
          </el-form-item>
          <div id="articleSetting">
            <slot name="bottom" />
          </div>
        </div>
      </div>
      <div class="editor-footer">
        <div class="left">
          <div class="count-container">
            <el-tooltip class="item" effect="dark" content="字数统计" placement="top">
              <span> 正文字数：{{ count }}</span>
            </el-tooltip>
            <el-button v-if="position==='content'" type="text" @click="goAnchorPoint">
              发文设置
              <i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-button v-if="position==='setting'" type="text" @click="goAnchorPoint">
              回到顶部
              <i class="el-icon-arrow-up el-icon--right" />
            </el-button>
          </div>

          <div class="tip-container">
            <slot name="desc" />

          </div>
        </div>
        <div class="tool">
          <slot name="footer" />
        </div>
      </div>
    </div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="400px"
      :before-close="handleClose">
      <el-progress :percentage="percentage" />
    </el-dialog>
  </div>
</template>
<script>
import '@wangeditor/editor/dist/css/style.css'
import { getToken } from '@/utils/auth'

import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { Boot } from '@wangeditor/editor'
import attachmentModule from '@wangeditor/plugin-upload-attachment'
if (Boot.plugins.length < 13) {
  Boot.registerModule(attachmentModule)
}
export default {
  components: { Editor, Toolbar },
  props: {
    form: {
      type: Object,
      default() {
        return {}
      }
    },
    error: {
      type: String,
      default: null
    },
    // 模式  simple 简洁模式  default 默认模式
    mode: {
      type: String,
      default() {
        return 'default'
      }
    },
    // 展示组件 author：作者  abstract:简述
    showInput: {
      type: Array,
      default() {
        return []
      }
    },
    catalog: {
      type: String,
      required: true
    },
    height: {
      type: String,
      default() {
        return '600px'
      }
    },
    placeholder: {
      type: String,
      default() {
        return '请输入内容...'
      }
    }
  },
  data() {
    var uploadConfig = {
      fieldName: 'file',
      maxFileSize: 5 * 1024 * 1024,
      maxNumberOfFiles: 10,
      meta: {
      },
      metaWithUrl: false,
      headers: {
        'Access-Token': getToken(),
        'ProjectsId': this.constants.PROJECTS_ID,
        'App-Id': this.constants.APP_ID,
        'App-Key': this.constants.APP_KEY
      },
      server: this.$FILE_SERVER + '/file/upload?catalogId=' + this.catalog,
      withCredentials: false,
      timeout: 30 * 1000,
      onBeforeUpload: (file) => {
        this.dialogVisible = true
        for (var item in file) {
          this.dialogTitle = file[item].name
        }
        return file
      },
      onProgress: (progress) => {
        this.percentage = progress
      },
      onSuccess: (file, res) => {
        setTimeout(() => {
          this.dialogVisible = false
        }, 1000)
      },
      onFailed: (file, res) => {
        this.handleFailed(file, res.data ? res.data : res.message)
      },
      onError: (file, err, res) => {
        this.handleFailed(file, err.toLocaleString())
      }
    }
    return {
      position: 'content',
      formRecord: {},
      count: 0,
      dialogTitle: '文件上传进度',
      dialogVisible: false,
      percentage: 0,
      editor: null,
      toolbarConfig: {
        excludeKeys: ['fullScreen'],
        insertKeys: {
          index: 24, // 自定义插入的位置
          keys: ['uploadAttachment'] // “上传附件”菜单
        }
      },
      editorConfig: {
        placeholder: this.placeholder,
        hoverbarKeys: {
          attachment: {
            menuKeys: ['downloadAttachment']
          }
        },
        MENU_CONF: {
          uploadImage: {
            allowedFileTypes: ['image/*'],
            ...uploadConfig,
            customInsert: (res, insertFn) => {
              var data = res.data
              insertFn(this.common.getFileView(data.uuid), data.originalName, this.common.getFileView(data.uuid))
            }
          },
          uploadVideo: {
            allowedFileTypes: ['video/*'],
            ...uploadConfig,
            customInsert: (res, insertFn) => {
              var data = res.data
              insertFn(this.common.getFileView(data.uuid))
            }
          },
          uploadAttachment: {
            ...uploadConfig,
            customInsert: (res, file, insertFn) => {
              var data = res.data
              insertFn(`附件-${file.name}`, this.common.getFileView(data.uuid))
              setTimeout(() => {
                this.dialogVisible = false
              }, 1000)
            }
          }
        }
      }
    }
  },
  watch: {
    form: function(val) {
      if (val) {
        this.formRecord = val
        this.$forceUpdate()
      }
    },
    'formRecord.title': function(val) {
      this.contentChange()
    },
    'formRecord.author': function(val) {
      this.contentChange()
    },
    'formRecord.contnetAbstract': function(val) {
      this.contentChange()
    }

  },
  mounted() {
    this.$nextTick(() => {
      this.count = this.T.removeHtmltag(this.form.content).length
      this.formRecord = this.form
      console.log(this.form)
    })
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy()
  },
  methods: {
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    onCreated(editor) {
      this.editor = Object.seal(editor)
    },
    onChange(editor) {
      this.formRecord = {
        ...this.formRecord,
        content: editor.getHtml()
      }
      this.contentChange()
      this.count = this.T.removeHtmltag(this.formRecord.content).length
    },
    handleFailed(file, message) {
      this.$modal.msgWarning(`文件${file.name}上传失败，失败原因：${message}`)
    },
    contentChange() {
      this.$emit('result', this.formRecord)
    },
    goAnchorPoint() {
      this.$nextTick(() => {
        if (this.position === 'content') {
          document.getElementById('articleSetting').scrollIntoView()
          this.position = 'setting'
        } else {
          document.getElementById('articleContent').scrollIntoView()
          this.position = 'content'
        }
      })
    }
  }

}
</script>
<style lang="scss" scoped>
  $width:850px;
  .docEditor{
    background-color: #fff;
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    overflow: auto;
    .editor-container{
      display: flex;
      flex-direction: column;
      flex:1;
      overflow: hidden;
    }
    .editor-toolBar{
      min-width: $width;
      background-color: #FCFCFC;
      margin: 0 auto;
    }
    .editor-main{
      width: $width;
      margin: 30px auto 0;
      background-color: #fff;
      padding: 35px 20px 20px;
      box-shadow: 0 2px 10px rgb(0 0 0 / 12%);
      flex: 1;
      overflow: auto;
      .ext-container{
        padding: 0 10px;
        border-bottom: 1px solid #EBEBEB;
      }
      .ext-container.bottom{
        border-top: 1px solid #EBEBEB;
        padding-top: 20px;
      }
    }
    .editor-footer{
      height: 50px;
      border-top: 1px solid #dcdfe6;
      line-height: 50px;
      text-align: center;
      display: flex;
      flex-direction: row;
      min-width: $width;
      margin: 0 auto;
      .left{
        font-size: 14px;
        color: #8D8D8D;
        display: flex;
        flex-direction: row;
        .tip-container{
          margin-left: 10px;
          font-size: 12px;
        }
        .count-container{
          button{
            color: #8D8D8D;
            margin-left: 10px;
            font-size: 14px;
          }
        }
      }
      .tool{
        flex: 1;
        text-align: right;
      }
    }

  }
</style>
